package org.tong.controller;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.tong.bean.FirstBean;
import org.tong.rabbitmq.RabbitmqService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@RestController
public class MyController implements ApplicationContextAware {

    //@Autowired
    private RabbitmqService rabbitmqService;

    @RequestMapping("/")
    public String index(@RequestParam(required = false, defaultValue = "frigg") String name) {
        HttpServletRequest request;
        HttpServletResponse response = null;
        return String.format("hello %s", name);
    }

    @GetMapping("/rabbitmq")
    public String rabbitmqMsg() {
        rabbitmqService.sendMsg(new Date().toString());
        return "rabbit->success";
    }

    //@Autowired
    private KafkaTemplate kafkaTemplate;

    @GetMapping("/kafka")
    public String kafkaMsg() {
        kafkaTemplate.send("test", new Date().toString()).addCallback(success -> {
            System.out.println("发送消息成功：" + success);
        }, failure -> {
            System.out.println("发送消息失败：" + failure.getMessage());
        });
        return "kafka->success";
    }

    @GetMapping("/beanLoad")
    public String beanLoad() {
        applicationContext.getBean(FirstBean.class);
        return "beanLoad";
    }

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
